// https://preapi.duckchain.io/user/ton/wallet/bind?address=UQDCvLQs1N5zZ9HQrHNG30R6ZkXNFi1bXK66oMiXEFTGSNnr


import DexieCtx from '@/utils/dexiectx';
import Config from '@/utils/config';
import { Api, TelegramClient } from 'telegram'
import { StringSession } from 'telegram/sessions'
import DuckchainTgweb from './duckchain_tgweb'
const stringUtil = require('@/utils/string')
const axiosUitl = require("@/utils/axios");

class DuckchainWallet {
    constructor() {
    }

    async bind_tg_wallet_by_phone_number(phone_number) {
        this.dexie = await DexieCtx.db()
        // const allAccounts = await this.dexie.accounts.where("phone").equal(phone_number).toArray()

        const account = await this.dexie.accounts.get({
            phone: phone_number
        })

        console.log(account)

        const strSession = new StringSession(account.session)
        const client = new TelegramClient(strSession, Config.API_ID, Config.API_HASH, {
            connectionRetries: 3,
            useWSS: true,
            timeout: 20,
        })
        client.phone = phone_number
        const dkweb = new DuckchainTgweb()
        dkweb.run(client)
        // invoke the wallet bind function.   

        const account_updated = await this.dexie.accounts.get({
            phone: phone_number
        })

        const game_account = await this.dexie.duckchain.get({
            phone: phone_number
        })

        let req_header = await this.get_req_header(game_account.tgweb)

        /* request update wallet function */
        // https://preapi.duckchain.io/user/ton/wallet/bind?address=UQDCvLQs1N5zZ9HQrHNG30R6ZkXNFi1bXK66oMiXEFTGSNnr

        const proxy = axiosUitl.parseProxy(account_updated.proxy)
        const axios = axiosUitl.createAxios(proxy)

        /* 1. Send the bind request */
        await axios.get('https://preapi.duckchain.io/user/ton/wallet/bind?address=' + account_updated.wallet_address, {
            headers: req_header
        }).then(response => {
            console.log('update result')
            // console.log(response)
        }).catch(function (error) {
            console.log('update failed...')
            console.log(error)
        })

        /* 2. Invoke user info interface to get the latest user information to make user privious update successful */
        await axios.get('https://preapi.duckchain.io/user/info', {
            headers: req_header
        }).then(response => {
            // console.log('updated ', response)
        }).catch(function (error) {
            console.log(error)
        })

        

    }

    async get_req_header(webSessionUrl) {
        if (webSessionUrl.startsWith("https://") == false) {
            console.error(`${this.tokenInfo.phone}  error session url ${webSessionUrl}`);
            return
        }
        let decodedWebSessionUrl = decodeURIComponent(webSessionUrl)
        let session = decodedWebSessionUrl.split("#tgWebAppData=")[1]
        session = session.split("&tgWebAppVersion")[0]

        // if ( session.indexOf('username') <= 0) { // At the first time, we need check if the user registed. If the URL value has not inclulded username value, it means the current account has not registed. Need register first. 
        let user_name = session.slice(session.indexOf('first_name') + 19, session.indexOf('last_name') - 9)
        user_name = user_name.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'');
        user_name = user_name + stringUtil.random_str(8)

        const req_header = {
            'content-type': 'application/json',
            authorization: 'tma ' + session
        }

        return req_header
    }
}

export default DuckchainWallet